package com.it.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * TODO
 *
 * @author: Coke
 * @DateTime: 2023/11/12/14:07
 **/
@Component
@Slf4j
public class ValidateCodeFilter extends OncePerRequestFilter {
    
    @Override
    protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        log.info("请求路径为：{}",requestURI);
        
        // 判断请求的是否为登录页面
        if (!"/login/doLogin".equals(requestURI)){ // 不是登录请求，直接放行
            doFilter(request,response,filterChain); //直接下一个
            return;
        }
        //校验验证码
        validateCode(request,response,filterChain);
    }
    
    private void validateCode (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
       // 获取用户输入的验证码
        String code = request.getParameter("code");
        // 获取session中存储的验证码
        HttpSession session = request.getSession();
        String login_captcha_code = (String) session.getAttribute("CAPTCHA_CODE");
        log.info("用户输入的验证码: {}, session中存储的验证码: {}", code, login_captcha_code);
        
        // 移除错误信息
        session.removeAttribute("captchaCodeErrorMsg");
        
        if (!StringUtils.hasText(code)){
            request.getSession().setAttribute("captchaCodeErrorMsg", "请输入验证码！");
            // 重定向到登录页面
            response.sendRedirect("/login/toLogin");
            return;
        }
        
        if (!StringUtils.hasText(login_captcha_code)){
            request.getSession().setAttribute("captchaCodeErrorMsg", "验证码错误！");
            // 重定向到登录页面
            response.sendRedirect("/login/toLogin");
        }
        
        if (!code.equalsIgnoreCase(login_captcha_code)){
            request.getSession().setAttribute("captchaCodeErrorMsg", "验证码输入错误！");
            // 重定向到登录页面
            response.sendRedirect("/login/toLogin");
        }
        // 删除session中的验证码
        session.removeAttribute("code");
        this.doFilter(request,response,filterChain);
    }
}
